var express = require('express');
var router = express.Router();
var path = require('path');
var fs = require('fs-extra');
var GoodsModel = require('../models/goods');
var UeditorModel = require('../models/ueditor');
var common = require('./common');
var checkLogin = require('./check').checkLogin;
var checkAdminLogin = require('./check').checkAdminLogin;
var multer = require('multer');
var storge = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/upload')
    },
    filename: function (req, file, cb) {
        var fileformat = (file.originalname).split('.');
        cb(null, file.fieldname + '-' + Date.now() + '.' + fileformat[fileformat.length - 1]);
    }
});
var upload = multer({storage: storge});

router.get('/', checkAdminLogin, function (req, res, next) {
    res.render('indexGoods', {title: 'shopping'});
});

router.get('/allGoods', function (req, res, next) {
    GoodsModel.getAllGoods()
        .then(function (result) {
            console.log(result);
            res.render('index', {
                title: 'shopping',
                goods: result
            })
        })
        .catch(function (e) {
            next(e);
        })
});

router.get('/getGoods', checkLogin, function (req, res, next) {
    console.log(req.query.goodsId);
    GoodsModel.getGoods(req.query.goodsId)
        .then(function (result) {
            console.log(result);
            var goodsTotal = 0;
            for (var i in result[0].info) {
                goodsTotal += parseInt(result[0].info[i].count);
            }
            res.render('goodsInfo', {
                title: "shopping",
                goodsInfo: result[0],
                goodsTotal: goodsTotal
            })
        })
        .catch(function (e) {
            next(e);
        })
});

router.get('/getShopkeeperGoods', checkAdminLogin, function (req, res, next) {
    var page = req.query.page || 1;
    GoodsModel.getShopkeeperGoods(req.session._id, page)
        .then(function (result) {
            GoodsModel.getGoodsCount({user: req.session._id})
                .then(function (count) {
                    var total = 1;
                    if (Math.ceil(parseInt(count) / 10) > 0) {
                        total = Math.ceil(parseInt(count) / 10);
                    }
                    res.render('goodsList', {
                        title: 'shopping',
                        goods: result,
                        page: page,
                        total: total
                    })
                })
                .catch(function (e) {
                    next(e);
                });
        })
        .catch(function (e) {
            next(e);
        })
});

router.get('/addGoods', checkAdminLogin, function (req, res, next) {
    res.render('addGoods', {
        title: 'shopping',
        goods: ''
    });
});
router.post('/addGoods', checkAdminLogin, function (req, res, next) {
    console.log(req.body);
    var images = req.body.files.split(",");
    var goodsInfo = {
        user: req.session._id,
        name: req.body.name,
        price: parseInt(req.body.price),
        info: common.setInfo(req.body),
        image: images,
        describe: req.body.editorValue,
        createdAt: common.nowDate(),
        updatedAt: common.nowDate()
    };
    GoodsModel.addGoods(goodsInfo)
        .then(function (result) {
            if (result.result.ok == 1) {
                console.log(result);
                var uedFilePath = {
                    goodsId: result.ops[0]._id,
                    images: common.getImgPath(req.body.editorValue),
                    video: common.getVideoPath(req.body.editorValue)
                };
                UeditorModel.addUeditor(uedFilePath)
                    .then(function (data) {
                        return res.json({status: 200, message: '商品添加成功'});
                    })
                    .catch(function (e) {
                        next(e);
                    })
            } else {
                common.delFiles(images);
                return res.json({status: 500, message: '商品添加失败'});
            }
        })
        .catch(function (e) {
            common.delFiles(images);
            next(e);
        })
});

router.post('/upload', upload.array('file'), function (req, res, next) {
    res.json({data: req.files});
});

router.post('/updateGoods', checkAdminLogin, function (req, res, next) {
    var images = req.body.files.split(",");
    var goodsInfo = {
        name: req.body.name,
        price: parseInt(req.body.price),
        info: common.setInfo(req.body),
        image: images,
        describe: req.body.editorValue,
        createdAt: common.nowDate(),
        updatedAt: common.nowDate()
    };
    GoodsModel.updateGoods(req.body.id, goodsInfo)
        .then(function (result) {
            if (result.result.ok == 1) {
                var uedFilePath = {
                    images: common.getImgPath(req.body.editorValue),
                    video: common.getVideoPath(req.body.editorValue)
                };
                UeditorModel.updateUeditor(req.body.id, uedFilePath)
                    .then(function (data) {
                        return res.json({status: 200, message: '修改成功'});
                    })
                    .catch(function (e) {
                        next(e);
                    });
            } else {
                common.delFiles(images);
                return res.json({status: 500, message: '修改失败'});
            }
        })
        .catch(function (e) {
            common.delFiles(images);
            next(e);
        })
});

router.post('/updateGoodsNum', checkLogin, function (req, res, next) {
    GoodsModel.updateGoodsNum(req.body.id, req.body.count)
        .then(function (result) {
            if (result.result.ok == 1) {
                return res.json({status: 200, message: '修改数目成功'});
            } else {
                return res.json({status: 500, message: '修改失败'});
            }
        })
        .catch(function (e) {
            next(e);
        })
});

router.get('/delGoods', checkAdminLogin, function (req, res, next) {
    GoodsModel.getGoods(req.query.id)
        .then(function (data) {
            for (var i in data[0].image) {
                fs.remove(data[0].image[i][0], function (err) {
                    if (err) {
                        console.log('err');
                    }
                })
            }

        })
        .catch(function (e) {
            next(e);
        });
    GoodsModel.delGoods(req.query.id)
        .then(function (result) {
            if (result.result.ok == 1 && result.result.n > 0) {
                return res.json({status: 200, message: '删除数据成功'})
            } else {
                return res.json({status: 500, message: '删除数据库失败'})
            }
        })
        .catch(function (e) {
            next(e);
        })
});

router.get('/clear', function (req, res, next) {
    var dirList = fs.readdirSync(path.join(__dirname, '../public/images/upload'));
    var status = false;
    GoodsModel.getAllGoods()
        .then(function (result) {
            dirList.forEach(function (fileItem) {
                result.some(function (item) {
                    item.image.some(function (imgItem) {
                        var fileName = imgItem[0].split('/').pop();
                        if (fileItem == fileName) {
                            status = false;
                            return true;
                            /*到文件跳出 image 循环 */
                        } else {
                            status = true;
                        }
                    });
                    if (!status) {
                        return true;
                        /*找到文件跳出 Goods 循环*/
                    }
                });
                if (status) {
                    fs.unlinkSync(path.join(__dirname, '../public/images/upload/' + fileItem));
                }
            });
            next();
        })
        .catch(function (e) {
            next(e);
        });
    UeditorModel.getAllUeditor()
        .then(function (result) {
            var imageList = fs.readdirSync(path.join(__dirname, '../public/images/ueditor'));
            var status1 = false;
            imageList.forEach(function (fileItem) {
                result.some(function (item) {
                    if(item.images.length > 0){
                        item.images.some(function (imgItem) {
                            var fileName = imgItem[0].split('/').pop();
                            if (fileItem == fileName) {
                                status1 = false;
                                return true;
                                /*到文件跳出 image 循环 */
                            } else {
                                status1 = true;
                            }
                        });
                        if (!status1) {
                            return true;
                            /*找到文件跳出 Goods 循环*/
                        }
                    }else{
                        status1 = true;
                    }
                });
                if (status1) {
                    fs.unlinkSync(path.join(__dirname, '../public/images/ueditor/' + fileItem));
                }
            });
            var videoList = fs.readdirSync(path.join(__dirname, '../public/video/ueditor'));
            var status2 = false;
            videoList.forEach(function (fileItem) {
                result.some(function (item) {
                    if (item.video.length > 0) {
                        item.video.some(function (imgItem) {
                            var fileName = imgItem[0].split('/').pop();
                            if (fileItem == fileName) {
                                status2 = false;
                                return true;
                            } else {
                                status2 = true;
                            }
                        });
                        if (!status2) {
                            return true;
                        }
                    } else {
                        status2 = true;
                    }
                });
                if (status2) {
                    fs.unlinkSync(path.join(__dirname, '../public/video/ueditor/' + fileItem));
                }
            });
            next();
        })
        .catch(function (e) {
            next(e);
        })
});

/*router.get('/p', function (req, res, next) {
 var k = '<p><video class="edui-upload-video  vjs-default-skin video-js" controls="" preload="none" width="200" height="200" src="/video/ueditor/891923261426896896.mp4" data-setup="{}"></video></p>';
 var myRe = k.match(/<video.*?(?:>)/gi);
 var imgPath = /src=['"]?([^'"]*)['"]?/i;
 myRe.forEach(function (item) {
 console.log(item.match(imgPath)[1]);
 });
 res.json(myRe)
 });*/

module.exports = router;


